package com.micai.springboot.filter;

import com.micai.springboot.entity.sys.SLogEntity;
import com.micai.springboot.queue.SLogQueue;
import com.micai.springboot.service.SLogService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 描述：访问请求拦截，保存操作日志
 * <p>
 * Author: 赵新国
 * Date: 2017/12/13 14:48
 */
public class SLogFilter implements Filter {

    private SLogService sLogService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        sLogService = webApplicationContext.getBean(SLogService.class);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String requestUrl = request.getRequestURI();
            String requestType = request.getMethod();
            // 保存日志信息
            SLogEntity sLogEntity = new SLogEntity();
            sLogEntity.setRequestUri(requestUrl);
            sLogEntity.setRequestType(requestType);
            // 日志信息加入消息队列
            SLogQueue.getInstance().push(sLogEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        chain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}
